import { useEffect, useRef, useState } from "react"

// 判断value是否为0的情况。两个！！表示返回布尔值 
export const isFalsy = (value:unknown) => (value === 0 ? false : !value)

export const isVoid = (value:unknown) => value === undefined || value === null || value === ''

// 在一个函数中改变一个传入对象本身是不好的
export const cleanObject = (object:{[key: string]:unknown }) => {
  // Object.assign({}, object)
  const result = {...object}
  Object.keys(result).forEach((key:string) => {
    // @ts-ignore
    const value = result[key]
    if(isVoid(value)) {
      // @ts-ignore
      delete result[key]
    }
  })
  return result
}

// 只挂载一次的初始化数据
export const useMount = (callback: () => void) => {
  useEffect(() =>{
    callback()
    // TODO 依赖项中加上callback会造成无限循环，这个和useCallback和useMemo有关系
    // eslint-disable-next-line react-hooks/exhaustive-deps
  },[])
}

// 后面用泛型来规范类型
// 防抖
export const useDebounce = <V>(value:V, delay?:number) => {
  const [debouncedValue, setDebouncedValue] = useState(value)

  useEffect(() => {
    // 每次在value变化之后设置一个定时器
    const timeout = setTimeout(() => setDebouncedValue(value), delay)
    // 在上一次useEffect使用之后运行，每次在上一个useEffect处理之后运行
    return () => clearTimeout(timeout)
  },[value, delay])

  return debouncedValue
}

// 数组
export const useArray = <T>(initialArray:T[]) => {
  const [value, setValue] = useState(initialArray)
  return {
    value,
    setValue,
    add: (item: T)  => setValue([...value, item]),
    clear: () => setValue([]), 
    removeIndex: (index:number) => {
      const copy = [...value]
      copy.splice(index, 1)
      setValue(copy)
    }
  }
}

// 动态改变React Title
export const useDocumentTitle = (title: string, keepOnUnmount = true) => {
  const oldTitle = useRef(document.title).current
  // 页面加载时：旧title“React App”
  // 页面加载后：新title
  useEffect(() => {
    document.title = title
  }, [title])

  useEffect(() => {
    return () => {
      if(!keepOnUnmount){
        // 如果不指定依赖，独到的就是旧title
        document.title = oldTitle
      }
    }
  },[keepOnUnmount, oldTitle])
}

export const resetRoute = () => window.location.href = window.location.origin